package com.springboot.test.springbootcrud.controller;

import com.springboot.test.springbootcrud.exception.UserNotFoundException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/12/28 10:33
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 浏览器客户端返回的都是json
     *
     * @param e
     * @return
     */
   /* @ResponseBody
    @ExceptionHandler(UserNotFoundException.class)
    public Map<String, Object> handleException(Exception e) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("code","user.notexit");
        map.put("message", e.getMessage());
        return map;
    }*/
    @ExceptionHandler(UserNotFoundException.class)
    public String handleException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        //传入我们自己的错误状态码:4xx,5xx
        /*
         *    Integer statusCode = (Integer) request
         *		.getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code", 500);

        map.put("code", "user.notexit");
        map.put("message", "用户出错了...");

        request.setAttribute("ext", map);
        //转发到/error请求
        return "forward:/error";
    }
}
